<?php
/**
 * Ecart
 *
 * This file is part of Ecart.
 *
 * Ecart is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Ecart is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Ecart.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category    Ecart
 * @package     Ecart_Admin
 * @copyright   Copyright 2008-2009 E-Cart LLC
 * @license     GNU Public License V3.0
 */

/**
 *
 * @category    Ecart
 * @package     Ecart_Admin
 * @subpackage  Controller
 * @author      Ecart Core Team <core@ecartcommerce.com>
 */
class Ecart_Admin_Customer_IndexController extends Ecart_Admin_Controller_Back
{
    public function indexAction()
    {
        $this->view->pageTitle = Ecart::translate('account')->__(
            'Manage Customers'
        );

        if ($this->_hasParam('customerId')) {
            $this->view->customerId = $this->_getParam('customerId');
        }

        $this->view->userForm = array();
        $this->view->valueSet = array();

        $value = Ecart::single('account/Customer_ValueSet_Value');

        $fields = Ecart::single('account/customer_field');
        $fieldGroups = Ecart::single('account/Customer_FieldGroup');
        $fieldGroups = $fieldGroups->getGroups($this->_langId);

        foreach ($fieldGroups as $fieldGroup){
            //getting all fields
            $this->view->userForm[$fieldGroup['id']]['title'] = $fieldGroup['title'];
            $this->view->userForm[$fieldGroup['id']]['is_active'] =
                $fieldGroup['is_active'];
            $this->view->userForm[$fieldGroup['id']]['fields'] =
                $fields->getFieldsByGroup($fieldGroup['id']);
            //getting only used valuesets
            foreach ($this->view->userForm[$fieldGroup['id']]['fields'] as $fd){
                if (!isset($fd['customer_valueset_id'])) continue;
                $this->view->valueSet[$fd['customer_valueset_id']]['values'] =
                    $value->getValues($fd['customer_valueset_id']);
            }
        }

        $this->render();
    }

    public function listAction()
    {
        $alpha = new Zend_Filter_Alpha();
        $params = array(
            'start' => (int) $this->_getParam('start', 0),
            'limit' => (int) $this->_getParam('limit', 25),
            'sort'  => $this->_getParam('sort', 'id'),
            'dir'   => $alpha->filter($this->_getParam('dir', 'ASC')),
            'getSitesName' => true
        );

        //extjs combobox compatible
        if ($query = $this->_getParam('query')) {
            $params['customer_email'] = $query;
            $params['firstname']      = $query;
            $params['lastname']       = $query;
        }

        $data = Ecart::single('account/customer')->getList($params);
        foreach ($data['accounts'] as &$item) {
            $item['password'] = '';
        }
        return $this->_helper->json->sendSuccess(array(
            'data'  => $data['accounts'],
            'count' => $data['count']
        ));
    }

    public function batchSaveAction()
    {
        $this->_helper->layout->disableLayout();

        $data = Zend_Json::decode($this->_getParam('data'));

        $modelCustomer = Ecart::single('account/customer');

        $success = 0;
        foreach ($data as $id => $values) {
            if (!$this->_isEmailValid($values['email'], $values['site_id'], $id)) {
                continue;
            }
            $customer = $modelCustomer->find($id)->current();
            $customer->setFromArray($values);
            $customer->save();
            $success++;
        }

        Ecart::message()->addSuccess(Ecart::translate('Ecart_Core')->__(
            '%d record(s) was saved successfully', $success
        ));

        return $this->_helper->json->sendSuccess();
    }

    public function deleteAction()
    {
        $this->_helper->layout->disableLayout();
        $data = Zend_Json_Decoder::decode($this->_getParam('data'));
        if (!sizeof($data)) {
            return;
        }
        Ecart::single('account/customer')->delete(
            $this->db->quoteInto('id IN(?)', $data)
        );
        return $this->_helper->json->sendSuccess();
    }

    public function getAddressListAction()
    {
        $this->_helper->layout->disableLayout();
        $addresses = array();
        if ($customerId = (int)$this->_getParam('customerId')) {
            $rowset = Ecart::single('account/customer_address')
                ->getSortListByCustomerId($customerId);

            foreach($rowset as $address) {
                $addresses[] = $address->toArray();
            }
        }

        return $this->_helper->json->setData($addresses)->sendSuccess();
    }

    public function getCustomerDataAction()
    {
        $this->_helper->layout->disableLayout();

        if (!$customer = Ecart::single('account/customer')->find((int)$this->_getParam('id'))->current()) {
            Ecart::message()->addError(Ecart::translate('Ecart_Account')->__(
                "Customer '%s' not found", $this->_getParam('id')
            ));
            return $this->_helper->json->sendFailure();
        }

        $result = array();
        $result['customer'] = $customer->toArray();

        // custom fields
        $result['custom_fields'] = array();
        foreach ($customer->getDetails() as $item) {
            if (isset($result['custom_fields']['field_' . $item['customer_field_id']])) {
                $result['custom_fields']
                    ['field_' . $item['customer_field_id']] .= ','
                        . $item['customer_valueset_value_id'];
            } else {
                $result['custom_fields']
                    ['field_' . $item['customer_field_id']] = isset($item['data']) ?
                        $item['data'] : $item['customer_valueset_value_id'];
            }
        }

        // address
        $result['address'] = array();
        $rowset = Ecart::single('account/customer_address')
            ->getSortListByCustomerId($customer->id);
        foreach($rowset as $address) {
            $result['address'][] = $address->toArray();
        }

        // orders
        $orders = Ecart::single('sales/order')->fetchAll(
            $this->db->quoteInto('customer_id = ?', $customer->id)
        );
        $orderStatus = Ecart_Collect_OrderStatus::collect();
        $orderStatusText = Ecart_Collect_OrderStatusText::collect();

        $result['order'] = array();
        foreach ($orders as $order) {
            $result['order'] = $order->toArray();

            $result['order']['product'] = array_values($order->getProducts());
            foreach($result['order']['product'] as &$product) {
                $product['price'] =
                    $product['price'] * $order->currency_rate;
                $product['final_price'] =
                    $product['final_price'] * $order->currency_rate;
                $product['product_subtotal'] =
                    $product['final_price'] * $product['quantity'];
            }

            if (isset($orderStatusText[$order['order_status_id']])) {
                $result['order']['status'] = $orderStatusText[$order['order_status_id']];
            } else {
                $result['order']['status'] = isset($orderStatus[$order['order_status_id']]) ?
                    $orderStatus[$order['order_status_id']] : $order['order_status_id'];
            }
        }

        // shopping cart
        $result['shopping_cart'] = array();
        if ($cart = Ecart::single('checkout/cart')->getCustomerCart($customer->id)) {
            $result['shopping_cart'] = array_values($cart->getProducts());
            foreach ($result['shopping_cart'] as &$product) {
                $product['attributes'] = array_values($product['attributes']);
            }
        }

        // wishlist
        $result['wishlist'] = Ecart::single('account/wishlist')->getList(array(
            'getProductNames' => true,
            'customerId' => $customer->id,
            'languageId' => Ecart_Locale::getLanguageId()
        ));

        return $this->_helper->json->sendSuccess(array(
            'data' => $result
        ));
    }

    public function saveCustomerAction()
    {
        $customerData = $this->_getParam('customer') + $this->_getParam('custom_fields');

        if (!$this->_isEmailValid($customerData['email'], $customerData['site_id'], $customerData['id'])) {
            return $this->_helper->json->sendFailure();
        }

        if (!$result = Ecart::single('account/customer')->save($customerData)) {
            return $this->_helper->json->sendFailure();
        }

        /**
         * @var Ecart_Account_Model_Customer_Row
         */
        $customer = Ecart::single('account/customer')->find($result['id'])->current();

        // address
        if ($this->_hasParam('address')) {
            foreach (Zend_Json::decode($this->_getParam('address')) as $address) {
                $customer->setAddress($address);
            }
        }

        // if customer is new
        if ($customer->id != $customerData['id']) {
            Ecart::message()->addSuccess(Ecart::translate('Ecart_Account')->__(
                'Account was created successfully'
            ));
            Ecart::dispatch('account_customer_register_success', array(
                'customer' => $customer,
                'password' => $result['password']
            ));
        } else {
            Ecart::message()->addSuccess(Ecart::translate('Ecart_Core')->__(
                'Data was saved successfully'
            ));
        }

        $this->_helper->json->sendSuccess(array(
            'data' => array('customer_id' => $customer->id)
        ));
    }

    protected function _isEmailValid($email, $siteId, $customerId = null)
    {
        $where = Ecart::db()->quoteInto('site_id = ?', $siteId);
        if (null !== $customerId) {
            $where .= ' AND ' . Ecart::db()->quoteInto('id <> ?', $customerId);
        }
        $validator = new Ecart_Validate_Exists(
            Ecart::single('account/customer'),
            'email',
            $where
        );
        if (!$validator->isValid($email)) {
            foreach ($validator->getMessages() as $message) {
                Ecart::message()->addError($message);
            }
            return false;
        }
        return true;
    }
}